<!--
Date: 2025-08-13
Copyright (c) 2025 Industrial Software Feature Database
-->
<template>
  <div class="structure_main">
    <div class="left">
      <el-tree highlight-current :default-expand-all="false" :data="treeData" ref="tree" node-key="id" :props="defaultProps" @node-click="handleNodeClick">
        <!-- @node-contextmenu="openMenu"  -->
        <template #default="{ node,data }">
          <span class="custom-tree-node">
            <span class="node-title" v-if="node.level === 3">{{ data.mark }}({{ node.label }}) </span>
            <span class="node-title" v-else>{{ node.label }} </span>
          </span>
        </template>
      </el-tree>

      <!-- 自定义右键菜单 -->
      <div v-show="menuVisible" :style="menuStyle" class="custom-menu" ref="wrapper">
        <ul>
          <li @click="handleMenuClick('add')">
            <el-button size="small" link type="primary" icon="Plus" :class="{'disable':menuLevel === 4}" :disabled="menuLevel === 4">添加</el-button>
          </li>
          <li @click="handleMenuClick('edit')">
            <el-button size="small" link type="primary" icon="Edit" :class="{'disable':menuLevel === 1}" :disabled="menuLevel === 1">编辑</el-button>
          </li>
          <li @click="handleMenuClick('delete')">
            <el-button size="small" link type="primary" icon="Delete" :class="{'disable':menuLevel === 1}" :disabled="menuLevel === 1">删除</el-button>
          </li>
        </ul>
      </div>
    </div>
    <div class="right">
      <div class="query">
        <el-form inline ref="queryFormRef" :model="queryParams" label-width="100px" size="small">
          <el-form-item label="上传日期:">
            <el-date-picker
              v-model="dateRangeCreateTime"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="daterange"
              range-separator="-"
              style="width: 200px"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="文件名称:">
            <el-input style="width: 200px" v-model="queryParams.fileName" placeholder="请输入文件名称" />
          </el-form-item>
          <el-form-item class="query_btns">
            <el-button size="small" type="primary" icon="search" @click="doQuery">查询</el-button>
            <el-button size="small" type="default" icon="refresh" @click="doReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="table_div">
        <el-button size="small" type="primary" class="upload_btn" @click="modelCompare">模型对比</el-button>
        <el-button size="small" type="primary" class="upload_btn" @click="batchDownload">批量下载</el-button>
        <el-table :data="tableData" v-loading="loading" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="left" />
          <el-table-column label="文件名称" align="left" prop="fileName"> </el-table-column>
          
          <!-- <el-table-column label="文件大小" align="left" width="150" prop="fileSizeWithUnit"> </el-table-column> -->
          <el-table-column label="部段名称" align="left" prop="sectionName"></el-table-column>
          <!-- <el-table-column label="所属批次" align="left" width="100" prop="batchNumber" show-overflow-tooltip></el-table-column>
          <el-table-column label="所属机型" align="left" prop="modelNumber"></el-table-column> -->
          <el-table-column label="上传日期" align="left" prop="createTime" width="150" show-overflow-tooltip> 
            <template #default="scope">{{ scope.row.uploadTimeStr.slice(0, 10) }}</template>
          </el-table-column>
          <el-table-column label="操作" align="left" width="250" fixed="right">
            <template #default="scope">
              <!-- <el-tooltip content="文件预览" placement="top"> -->
                <el-button size="small" link type="primary" icon="View" @click="view(scope.row)">预览</el-button>
                <el-button size="small" link type="primary" icon="Upload" @click="reUpload(scope.row)">重新上传</el-button>
              <!-- </el-tooltip> -->
              <!-- <el-tooltip content="下载" placement="top"> -->
                <el-button size="small" link type="primary" icon="Download" @click="handleDownload(scope.row)">下载</el-button>
              <!-- </el-tooltip> -->
              <!-- <el-tooltip content="数据质量报告" placement="top"> -->
                <el-button size="small" link disabled type="primary" icon="Memo" @click="viewQualityReport(scope.row)">数据质量报告</el-button>
                
                <el-button size="small" link type="primary" icon="Delete" @click="deleteBdf(scope.row)">删除</el-button>
              <!-- </el-tooltip> -->
            </template>
          </el-table-column>
        </el-table>
        <div class="pagenation">
          <!-- <el-pagination
            v-show="total > 0"
            layout="prev, pager, next,jumper"
            v-model:page="queryParams.pageQuery.pageNum"
            v-model:limit="queryParams.pageQuery.pageSize"
            v-model:current-page="queryParams.pageQuery.pageNum"
            :total="total"
            @current-change="handleCurrentChange"
          /> -->
          <pagination
            v-show="total > 0"
            style="margin-top: 0;"
            v-model:page="queryParams.pageQuery.pageNum"
            v-model:limit="queryParams.pageQuery.pageSize"
            :total="total"
            :background="false"
            layout="total, sizes, prev, pager, next, jumper"
            @pagination="handleCurrentChange"
          />
        </div>
      </div>
    </div>
    <el-dialog v-model="uplaodVisible" title="重新上传" width="600px" append-to-body>
      <div class="bdf-reupload__main" style="padding-left: 30px;" v-loading="uploadLoading">
        <div style="margin-bottom: 20px;">原文件：{{primaryFileName}}.{{primarySuffix}}</div>
        <el-upload
          style="width: 100%;"
          @change="handleChange"
          :on-remove="handleRemove"
          :file-list="fileList"
          :show-file-list="true"
          :auto-upload="false"
          :multiple="false"
          :limit="1"
          action="#"
        >
          <el-button size="large" icon="UploadFilled">选取文件</el-button>
          <!-- <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">
            拖拽到这里或者 <em>点击上传</em>
          </div> -->
        </el-upload>
        
      </div>
      <template #footer>
        <div class="dialog-footer" style="text-align: center;">
          <el-button size="small" @click="uplaodVisible = false">取消</el-button>
          <el-button type="primary" size="small" @click="sureUpload">确认上传</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  <BdfPreView
    v-if="showBdf"
    :visible="showBdf"
    :bdfItem="bdfItem"
    @handleEvent="handleBdfEvent"
   />
   <Contrast
    v-if="addVisible"
    :addVisible="addVisible"
    :operateType="operateType"
    :compareRecordId="compareRecordId"
    @handleEvent="handleEvent"
  />
  
</template>
<script setup name="MeshTreeTable">
import BdfPreView from './BdfPreView.vue';
import Contrast from '../../compare/components/Contrast.vue';
import { getDicts } from '@/api/system/dict/data';
import { downloadFile } from '@/utils/index';
import { getNaturalMeshTree, previewNaturalMesh, getNaturalMeshList, downloadNaturalMeshFile, reuploadNaturalMeshFile, deleteNaturalMeshFile } from '@/api/dataAcquisition';
import { bdfFileFunc } from "../fileDownload.js";
import { to } from 'await-to-js';
const { downloadFileWithAxios, batchDownloadBdfFile } = bdfFileFunc();
const treeData = ref([]);
const loading = ref(false);
const uploadLoading = ref(false);
const showBdf = ref(false);
const bdfItem = ref('');
const addVisible = ref(false); // 新增对比弹窗
const operateType = ref(''); // 新增对比弹窗类型
const compareRecordId = ref(''); // 新增对比弹窗记录id
const defaultProps = {
  children: 'children',
  label: 'name'
};
const sectionDicts = ref([]);
const menuVisible = ref(false);
const mentRemoveCheck = ref(false);
const menuStyle = ref({
  left: 0,
  top: 0
});
const tableData = ref([]);
const total = ref(0);
const dateRangeCreateTime = ref(['', '']);
const queryParams = ref({
  pageQuery: {
    pageNum: 1,
    pageSize: 10,
  },
  modelNumber: "",
  sectionNumber: "",
  batchNumber: "",
  beginUploadTime: '',
  endUploadTime: '',
  fileName: ''
})
const formRef = ref(null);
const wrapper = ref(null);
const showAdd = ref(false);
const formData = ref({ name: '', mark: '', taskDefault: '' });
const nodeContent = ref(null);
const editFlag = ref(false);
const menuLevel = ref(null);
const selectionList = ref([]);
const modelCompare = () => {
  operateType.value = 'Add';
  compareRecordId.value = null;
  addVisible.value = true;
}
const fileList = ref([]);
const submitFile = ref(null);
const uplaodVisible = ref(false);
const bdfId = ref(null);
const primaryFileName = ref('');
const primarySuffix = ref('');
const view = (row) => {
  bdfItem.value = row
  showBdf.value = true;
}
const handleEvent = (data) => {
  addVisible.value = false;
  if (data?.type === 'refresh') {
    doQuery();
  } else if (data?.type === 'cancel') {

  };
};
// 重新上传 
const reUpload = (row) => {
  submitFile.value = null;
  fileList.value = [];
  bdfId.value = row._id;
  primaryFileName.value = row.fileName;
  primarySuffix.value = row.fileSuffix;
  nextTick(() => {
    uplaodVisible.value = true;
  })
  
}
const handleUpload = () => {
  uploadLoading.value = true;
  const formData = new FormData();
  formData.append('file', submitFile.value);
  formData.append('_id', bdfId.value);
  reuploadNaturalMeshFile(formData).then(res => {
    if (res) {
      uplaodVisible.value = false;
      ElMessage({ showClose: true, message: '重新上传成功', type: 'success' });
      doQuery();
    }
  }).catch(err => {
    uploadLoading.value = false;
  }).finally(() => {
    uploadLoading.value = false;
  })
}
const sureUpload = () => {
  if (!submitFile.value) {
    ElMessage({ showClose: true, message: '请选择文件上传', type: 'error' });
    return;
  }
  let suffix = submitFile.value.name.split('.')
  if (primarySuffix.value !== suffix[1]) {
    ElMessage({ showClose: true, message: '重新上传文件和原文件类型不同，请重新上传', type: 'error' });
    return;
  }
  if (primaryFileName.value !== suffix[0]) {
    ElMessageBox.confirm(`文件名称不同，请确认是否继续上传？`, `提示`, {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      handleUpload();
    });
  } else {
    handleUpload();
  }
}
const handleRemove = (file) => {
  submitFile.value = null;
};
const handleChange = (file) => {
  submitFile.value = file.raw;
};
// 删除
const deleteBdf = (row) => {
  ElMessageBox.confirm(`是否确认删除${row.fileName}？`, `提示`, {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteNaturalMeshFile(row._id)
      .then((res) => {
        if (res) {
          ElMessage({ showClose: true, message: '删除成功。', type: 'success' });
          doQuery();
        }
      })
      .catch(() => { });
  });
}
// 节点点击右侧列表更新
const handleNodeClick = (data, TreeNode) => {
  if (TreeNode.level == 1) {
    queryParams.value.modelNumber = data.mark;
    queryParams.value.batchNumber = '';
    queryParams.value.sectionNumber = '';
  } else if (TreeNode.level == 2) {
    queryParams.value.modelNumber = TreeNode.parent.data.mark;
    queryParams.value.batchNumber = TreeNode.data.mark;
    queryParams.value.sectionNumber = '';
  } else if (TreeNode.level == 3) {
    queryParams.value.modelNumber = TreeNode.parent.parent.data.mark;
    queryParams.value.batchNumber = TreeNode.parent.data.mark;
    queryParams.value.sectionNumber = TreeNode.data.mark;
  }
  queryParams.value.pageQuery.pageNum = 1;
  doQuery();
}
const handleDownload = (row) => {
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '文件下载中，请稍候...',
    background: 'rgba(0, 0, 0, 0.7)',
  });
  downloadFileWithAxios(row._id, loadingInstance, 1);
}
const batchDownload = async () => {
  if (!selectionList.value || selectionList.value.length == 0) {
    ElMessage({ showClose: true, message: '请先选择文件', type: 'error' });
    return;
  }
  
  // batchDownloadBdfFile(ids, loadingInstance)

  /** 批量下载 */
  const [err, res] = await to(
    ElMessageBox.prompt('请输入ZIP包文件名：', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      closeOnClickModal: false,
      // inputPattern: /^.{5,20}$/,
      // inputErrorMessage: '用户密码长度必须介于 5 和 20 之间',
      inputValidator: (value) => {
        if (!value) {
          return '文件名不能为空';
        }
        if (/<|>|"|'|\||\\/.test(value)) {
          return '不能包含非法字符：< > " \' \\\ |';
        }
      }
    })
  );
  if (!err && res) {
    const loadingInstance = ElLoading.service({
      lock: true,
      text: '文件下载中，请稍候...',
      background: 'rgba(0, 0, 0, 0.7)',
    });
    let ids = selectionList.value.map(item => item._id);
    batchDownloadBdfFile(ids, res.value, loadingInstance)
  }
}
const handleDelete = (row) => {}
const viewQualityReport = (row) => {}
const handleBdfEvent = (data) => {
  showBdf.value = false;
}
const handleCurrentChange = () => {
  // queryParams.value.pageQuery.pageNum = val;
  doQuery();
};  
const doQuery = () => {  
  loading.value = true;
  tableData.value = [];
  queryParams.value.uploadTimeStartTime = dateRangeCreateTime.value[0];
  queryParams.value.uploadTimeEndTime = dateRangeCreateTime.value[1];
  getNaturalMeshList(queryParams.value).then((res) => {
    if (res.rows) {
      loading.value = false;
      tableData.value = res.rows;
      total.value = res.total;
    }
  })
  .catch(() => {
    loading.value = false;
  }).finally(() => {
    loading.value = false;
  });
};
const doReset = () => {
  queryParams.value = {
    pageQuery: {
      pageNum: 1,
      pageSize: 10,
    },
    modelNumber: "",
    sectionNumber: "",
    batchNumber: "",
    beginUploadTime: '',
    endUploadTime: '',
    fileName: ''
  };
  dateRangeCreateTime.value = ['', ''];
  doQuery();
};
const handleSelectionChange = (val) => {
  selectionList.value = val;
};
// 查询类型字典
getDicts('sys_common_constants').then((res) => {
  if (res.data) {
    sectionDicts.value = JSON.parse(res.data.find(item => item.dictLabel == 'structure_definition_section_name')?.dictValue);
  }
});
const handleMenuClick = (command) => {
  formData.value = {};
  if (command === 'add') {
    showAdd.value = true;
    editFlag.value = false;
    formData.value.name = '';
    formData.value.mark = '';
    formData.value.taskDefault = '';
  }
  if (command === 'edit') {
    showAdd.value = true;
    editFlag.value = true;
    formData.value.name = nodeContent.value.label;
    formData.value.mark = nodeContent.value.mark;
    formData.value.taskDefault = nodeContent.value.taskDefault;
  }
  formRef.value && formRef.value.clearValidate();
  if (command === 'delete') {    
    showAdd.value = false;
    ElMessageBox.confirm('删除后目录下的所有文件均将删除，是否确认删除此目录？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      deleteStructureMenu(nodeContent.value.id)
        .then((res) => {
          if (res) {
            ElMessage({ showClose: true, message: '删除成功。', type: 'success' });
            queryTreeMenu();
          }
        })
        .catch(() => {
          ElMessage({ showClose: true, message: '删除失败。', type: 'error' });
        });
    });
  }
  menuVisible.value = false;
};
// 右键点击
const openMenu = (event, data, node, element) => {
  menuLevel.value = node.level;
  nodeContent.value = data;
  // 显示菜单
  menuVisible.value = true;
  // 阻止默认的右键菜单显示
  event.preventDefault();
  // 设置菜单的位置
  menuStyle.value.left = 210 + 'px';
  menuStyle.value.top = event.clientY - 82 + 'px';
};
const handleClick = (event) => {
  // 检查点击是否发生在外部
  if (wrapper.value && !wrapper.value.contains(event.target)) {
    menuVisible.value = false;
  }
};

const queryTreeMenu = () => {
  getNaturalMeshTree().then((res) => {
    if (res?.data) {
      treeData.value = res?.data || [];
    }
  });
};
onMounted(() => {
  queryTreeMenu();
  doQuery();
});
</script>
<style lang="less" scoped>
.structure_main {
  padding-top: 10px;
  font-size: 12px;
  display: flex;
  // height: calc(100vh - 190px);
  // overflow: auto;
  .left {
    width: 300px;
    position: relative;
    border-right: 1px solid #ebebeb;
    // padding: 10px;
    padding-bottom: 20px;
    height: calc(100vh - 200px);
    overflow: auto;
    .title {
      font-weight: 600;
    }
    .custom-menu {
      position: absolute;
      background-color: #fff;
      border: 1px solid #ebebeb;
      border-radius: 3px;
      width: 80px;
      z-index: 1000;
      font-size: 12px;
      ul {
        margin: 0;
        padding: 5px 0;
        list-style: none;
        font-size: 12px;
      }
      ul li {
        padding: 3px 15px;
        cursor: pointer;
        font-size: 12px;
        display: flex;
        align-items: center;
      }
      ul li:hover {
        background-color: #eee;
      }
    }
    :deep(.el-tree-node__label) {
      font-size: 12px;
    }
    .custom-tree-node{
      font-size: 12px;
    }
  }
  .right {
    padding: 10px 10px 10px 20px;
    height: calc(100vh - 210px);
    overflow: auto;
    flex: 1;
    .pagenation {
      display: flex;
      justify-content: end;
      padding: 10px;
    }
  }
  .disable{
    color:#d9d9d9;
  }
}
</style>